<template>
    <div class="index">
        <div class="bg_music" @tap="audioPlay">
            <image src="../../static/images/music_icon.png" class="musicImg" :class="isPlay?'music_icon':''"/>
            <image src="../../static/images/music_play.png" class="music_play" :class="isPlay?'pauseImg':'playImg'"/>
        </div>
        <audio id="myAudio" :src="audioUrl" autoplay loop></audio>
        <div class="calendar_box" :class="showCalendar?'':'hide_box'">
            <image class="btn" src="../../static/images/calendar.png" @tap="switchCalendar"/>
            <div class="left" :class="showCalendar?'':'hide_left'">
                <div class="circle">
                    <span class="day">{{day}}</span>
                    <span class="month">{{month}}月</span>
                </div>
                <div class="addressWeather">
                    <p class="address">{{address}}</p>
                    <p class="weather">{{weather}}<span>{{temperature}}</span></p>
                    <p class="winddirection">{{winddirection}}</p>
                </div>
            </div>
            <calendar
                :class="showCalendar?'':'hide_right'"
                class="right"
                weeks-type="en"
                cell-size="20"
                :header="showHeader"
                show-more-days=true
                calendar-style="demo4-calendar"
                board-style="demo4-board"
                :days-color="demo4_days_style"
                @dayClick="dayClick"
            />
        </div>
        <image v-if="showPost" class="post_mood" src="../../static/images/post_mood.png" @tap="postMood"/>
        <ul class="list">
            <li class="item" v-for="(item, index) in diaryList" :key="item._id" @tap="toDetail(item)">
                <image class="like" src="../../static/images/like_active.png" v-if="likeList[index] === '2'" @tap.stop="toLike(item._id, '1', item.like)"/>
                <image class="like" src="../../static/images/like.png" v-if="likeList[index] === '1'" @tap.stop="toLike(item._id, '2', item.like)"/>
                <image class="img" :src="item.url" mode="aspectFill"/>
                <p class="desc">{{item.desc}}</p>
                <div class="name-weather">
                    <span class="name">{{item.name}}</span>
                    <span class="weather">{{item.weather}}</span>
                </div>
                <p class="time-address">
                    <span class="time">{{item.time}}</span>
                    <!-- <span class="address">{{item.address}}</span> -->
                </p>
            </li>
        </ul>
        <div class="loading-container" v-if="getSrcFlag">
            <loading></loading>
        </div>
        <div class="dialog" v-if="showDialog">
            <div class="box">
                <h3>提示</h3>
                <p>是否授权使用点赞功能？</p>
                <div class="bottom">
                    <button class="cancel" @tap="hideDialog">取消</button>
                    <button class="confirm" lang="zh_CN" open-type="getUserInfo" @getuserinfo="login">确认</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Loading from 'components/loading'
import amapFile from 'common/js/amap-wx.js'
import tools from 'common/js/tools'
export default {
  name: 'Index',
  data () {
    return {
      isPlay: true,
      audioCtx: '',
      audioUrl: '',
      openId: '',
      days_count: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate(),
      demo4_days_style: [],
      showHeader: false,
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
      showCalendar: true,
      address: '',
      weather: '',
      temperature: '',
      winddirection: '',
      diaryList: [],
      showPost: false,
      getSrcFlag: true,
      likeList: [],
      userInfo: null,
      showDialog: false,
      tempObj: null
    }
  },
  onLoad () {
    const that = this
    wx.showNavigationBarLoading()
    that.setCalendarStyle()
    that.audioCtx = wx.createAudioContext('myAudio')
    that.getOpenId()
  },
  onShow () {
    const that = this
    that.isPlay = true
    that.getWeather()
    that.getMusicUrl()
  },
  components: {
    Loading
  },
  methods: {
    audioPlay () {
      const that = this
      if (that.isPlay) {
        that.audioCtx.pause()
        that.isPlay = !that.isPlay
        tools.showToast('您已暂停音乐播放~')
      } else {
        that.audioCtx.play()
        that.isPlay = !that.isPlay
        tools.showToast('背景音乐已开启~')
      }
    },

    getMusicUrl () {
      const that = this
      const db = wx.cloud.database()
      const music = db.collection('music')
      music.get().then(res => {
        that.audioUrl = res.data[0].musicUrl
        that.audioCtx.loop = true
        that.audioCtx.play()
      })
    },

    getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user',
        data: {}
      }).then(res => {
        that.openId = res.result.openid
        if (that.openId === '媳妇的openId' || that.openId === '我的openId') {
          that.showPost = true
        }
        that.getDiaryList()
      })
    },

    setCalendarStyle () {
      const that = this
      for (let i = 1; i <= that.days_count; i++) {
        if (i === that.day) {
          that.demo4_days_style.push({
            month: 'current', day: i, color: 'white', background: '#46c4f3'
          })
        } else {
          that.demo4_days_style.push({
            month: 'current', day: i, color: '#333'
          })
        }
      }
    },

    switchCalendar () {
      const that = this
      that.showCalendar = !that.showCalendar
    },

    getWeather () {
      const that = this
      let myAmapFun = new amapFile.AMapWX({key: tools.key})
      myAmapFun.getWeather({
        success (res) {
          // 成功回调
          that.address = res.liveData.city
          that.weather = res.liveData.weather + ' '
          that.temperature = res.liveData.temperature + '℃'
          that.winddirection = res.liveData.winddirection + '风' + res.liveData.windpower + '级'
        },
        fail (info) {
          // 失败回调
          console.log(info)
        }
      })
    },

    dayClick (e) {
      let temp = e.mp.detail
      wx.showToast({
        title: '农历' + temp.lunarMonth + temp.lunarDay,
        icon: 'none',
        duration: 1000
      })
    },

    getDiaryList () {
      const that = this
      wx.cloud.callFunction({
        name: 'diaryList',
        data: {}
      }).then(res => {
        that.getSrcFlag = false
        that.diaryList = res.result.data.reverse()
        that.likeList = []
        that.diaryList.forEach((item, index) => {
          item.like.forEach(itemSecond => {
            if (itemSecond.openId === that.openId) {
              that.likeList.push(itemSecond.type)
            }
          })
          if (that.likeList.length < index + 1) {
            that.likeList.push('1')
          }
        })
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh()
      })
    },

    postMood () {
      const that = this
      wx.navigateTo({
        url: '/pages/postMood/main?address=' + that.address + '&openId=' + that.openId + '&weather=' + that.weather
      })
    },

    toDetail (obj) {
      // const that = this
      wx.navigateTo({
        url: '/pages/diaryDetail/main?name=' + obj.name + '&url=' + obj.url + '&desc=' + obj.desc + '&address=' + obj.address + '&likeList=' + JSON.stringify(obj.like)
      })
    },

    toLike (id, type, arr) {
      const that = this
      that.tempObj = {
        id: id,
        type: type,
        like: arr
      }
      wx.getSetting({
        success (res) {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function (res) {
                that.userInfo = res.userInfo
                wx.cloud.callFunction({
                  name: 'like',
                  data: {
                    id: id,
                    type: type,
                    like: arr,
                    name: that.userInfo.nickName
                  }
                }).then(res => {
                  if (type === '1') {
                    tools.showToast('取消点赞成功')
                  } else {
                    tools.showToast('点赞成功~')
                  }
                  that.getOpenId()
                })
              }
            })
          } else {
            that.showDialog = true
          }
        }
      })
    },

    hideDialog () {
      const that = this
      that.showDialog = false
    },

    login (e) {
      const that = this
      console.log(that.tempObj, e)
      if (e.target.errMsg === 'getUserInfo:ok') {
        wx.getUserInfo({
          success: function (res) {
            that.userInfo = res.userInfo
            wx.cloud.callFunction({
              name: 'like',
              data: {
                id: that.tempObj.id,
                type: that.tempObj.type,
                like: that.tempObj.like,
                name: that.userInfo.nickName
              }
            }).then(res => {
              if (that.tempObj.type === '1') {
                tools.showToast('取消点赞成功')
              } else {
                tools.showToast('点赞成功~')
              }
              that.getOpenId()
            })
          }
        })
      }
      that.showDialog = false
    }
  },

  onPullDownRefresh () {
    const that = this
    that.getSrcFlag = true
    wx.showNavigationBarLoading()
    that.getOpenId()
  },

  onShareAppMessage: function (res) {
    return {
      path: '/pages/index/main'
    }
  }
}
</script>

<style scoped lang="stylus">
.loading-container
    position fixed
    width 100%
    height 100%
    top 0
    bottom 0
    left 0
    right 0
    background #fff
    margin auto
    display flex
    justify-content center
    align-items center
    z-index 9999
@-webkit-keyframes musicRotate
  from
    -webkit-transformb rotate(0deg)
  to
    -webkit-transform rotate(360deg)
@-webkit-keyframes musicStop
  from
    -webkit-transform rotate(20deg)
  to
    -webkit-transform rotate(0deg)
@-webkit-keyframes musicStart
  from
    -webkit-transform rotate(0deg)
  to
    -webkit-transform rotate(20deg)
@-webkit-keyframes fromLeft
  from
    -webkit-transform translateX(-250rpx)
  to
    -webkit-transform translateX(0)
@-webkit-keyframes toLeft
  from
    -webkit-transform translateX(0)
  to
    -webkit-transform translateX(-250rpx)
@-webkit-keyframes fromRight
  from
    -webkit-transform translateX(500rpx)
  to
    -webkit-transform translateX(0)
@-webkit-keyframes toRight
  from
    -webkit-transform translateX(0)
  to
    -webkit-transform translateX(500rpx)
@-webkit-keyframes decreaseHeight
  from
    height 500rpx
  to
    height 80rpx
@-webkit-keyframes addHeight
  from
    height 80rpx
  to
    height 500rpx
.index
  height 100%
  position relative
  .bg_music
    position fixed
    right 0
    top 20rpx
    width 100rpx
    z-index 99
    display flex
    justify-content flex-start
    align-items flex-start
    .musicImg
      width 60rpx
      height 60rpx
    .music_icon
      animation musicRotate 3s linear infinite
    .music_play
      width 28rpx
      height 60rpx
      margin-left -10rpx
      transform-origin top
      -webkit-transform rotate(20deg)
    .playImg
      animation musicStop 1s linear forwards
    .pauseImg
      animation musicStart 1s linear forwards
  #myAudio
    display none
  .calendar_box
    display flex
    justify-content space-around
    align-items center
    position relative
    min-height 80rpx
    background -webkit-linear-gradient(#66cdcc 0%, #ffffff 100%)
    .btn
      position absolute
      width 60rpx
      height 60rpx
      left 30rpx
      top 10rpx
      z-index 99
    .left
      flex 1
      display flex
      flex-direction column
      justify-content center
      align-items center
      padding-top 80rpx
      .circle
        height 160rpx
        width 160rpx
        border-radius 100rpx
        background #ED758D
        margin 0 auto 30rpx
        display flex
        flex-direction column
        justify-content center
        align-items center
        .day
          color #fff
          font-size 30rpx
        .month
          color #e6e6e6
          font-size 50rpx
      .addressWeather
        height 200rpx
        width 100%
        display flex
        flex-direction column
        justify-content center
        align-items center
        .address
          text-align center
          font-size 40rpx
          margin-bottom 20rpx
          color #1296db
        .weather
          text-align center
          font-size 50rpx
          color #63A92C
          margin-bottom 20rpx
          span
            color #F86635
        .winddirection
          text-align center
          font-size 30rpx
          color #773917
    .hide_left
      animation toLeft 0.3s linear forwards
    .right
      flex 2
      padding-top 80rpx
    .hide_right
      animation toRight 0.3s linear forwards
  .hide_box
    animation decreaseHeight 0.05s linear forwards
    -webkit-animation-delay 0.3s
  .post_mood
    position fixed
    right 60rpx
    bottom 60rpx
    height 100rpx
    width 100rpx
    box-shadow 0 0 20rpx rgba(0, 0, 0, 0.1)
    border-radius 50%
    background #fff
    z-index 99
  .list
    width 690rpx
    padding 50rpx 30rpx
    display flex
    justify-content flex-start
    align-items flex-start
    flex-wrap wrap
    .item
      width 330rpx
      margin-right 30rpx
      &:nth-of-type(2n+0)
        margin-right 0
      display flex
      flex-direction column
      justify-content flex-start
      align-items flex-start
      box-shadow 0 0 20rpx rgba(0, 0, 0, 0.1)
      margin-bottom 40rpx
      padding-bottom 30rpx
      border-radius 0 0 16rpx 16rpx
      position relative
      .like
        position absolute
        right 10rpx
        top 10rpx
        z-index 9
        background #fff
        height 30rpx
        width 30rpx
        padding 0
        margin 0
        border-radius 50%
        padding 10rpx
      .img
        width 100%
        height 180rpx
        margin-bottom 20rpx
        border-radius 16rpx 16rpx 0 0
      .desc
        line-height 60rpx
        height 60rpx
        color #333
        padding-left 20rpx
        width 290rpx
        word-wrap break-word
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
        font-size 30rpx
      .name-weather
        height 50rpx
        line-height 50rpx
        color #66cdcc
        font-size 24rpx
        padding-left 20rpx
        display flex
        width 290rpx
        justify-content space-between
        align-items center
        .weather
          color #63A92C
      .time-address
        height 40rpx
        line-height 40rpx
        color #773917
        font-size 24rpx
        padding-left 20rpx
        display flex
        width 290rpx
        justify-content space-between
        align-items center
        .address
          color #999
  .dialog
    position fixed
    top 0
    bottom 0
    left 0
    right 0
    background rgba(0, 0, 0, 0.5)
    z-index 99
    display flex
    justify-content center
    align-items center
    .box
      width 500rpx
      height 240rpx
      background #fff
      border-radius 16rpx
      display flex
      flex-direction column
      justify-content flex-start
      align-items center
      h3
        height 80rpx
        line-height 80rpx
        font-size 30rpx
        color #333
        font-weight 600
      p
        height 50rpx
        line-height 50rpx
        font-size 28rpx
        color #333
        margin-bottom 30rpx
      .bottom
        height 80rpx
        width 100%
        display flex
        justify-content space-around
        align-items center
        button
          color #333
          width 500rpx
          font-size 30rpx
          height 80rpx
          line-height 80rpx
          font-weight 600
          background #fff
          &::after
            border none
        .confirm
          color #63A92C
</style>
